package mobile.game.common.support;



import java.lang.reflect.InvocationTargetException;
import java.util.List;

import mobile.game.core.Port;
import mobile.game.core.Service;
import mobile.game.core.support.ClassFinder;
import mobile.game.core.support.log.LogCore;

public class ClassFactory {

	/**
	 * 创建Port的子类实例
	 * @param portType
	 * @param name
	 * @return
	 */
	public static Port createPort(String portType, String name) {
		List<Class<?>> allClass = ClassFinder.getAllClass("mobile.game");
		for (Class<?> matchClass : allClass) {
			if (!Port.class.isAssignableFrom(matchClass)) {
				continue;
			}
			
			if (portType.equals(matchClass.getSimpleName())) {
				try {
					Port newPort = (Port)matchClass.getConstructor(String.class).newInstance(name);
					return newPort;
				} catch (InstantiationException | IllegalAccessException | IllegalArgumentException
						| InvocationTargetException | NoSuchMethodException | SecurityException e) {
					LogCore.core.error("", e);
					return null;
				}
			}
			
		}
		
		return null;
	}
	
	/**
	 * 创建Service子类的实例
	 * @param serviceType
	 * @param name
	 * @return
	 */
	public static Service createService(String serviceType, String name) {
		List<Class<?>> allClass = ClassFinder.getAllClass("mobile.game");
		for (Class<?> matchClass : allClass) {
			if (!Service.class.isAssignableFrom(matchClass)) {
				continue;
			}
			
			if (serviceType.equals(matchClass.getSimpleName())) {
				try {
					Service newPort = (Service)matchClass.getConstructor(String.class).newInstance(name);
					return newPort;
				} catch (InstantiationException | IllegalAccessException | IllegalArgumentException
						| InvocationTargetException | NoSuchMethodException | SecurityException e) {
					LogCore.core.error("", e);
					return null;
				}
			}
		}
		
		return null;
	}

}
